<template>
  <CustomerLayout>
    <div class="history-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>浏览历史</h2>
        
      </div>
      
      <!-- 历史类型切换 -->
      <div class="history-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="店铺历史" name="stores"></el-tab-pane>
          <el-tab-pane label="商品历史" name="foods"></el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 店铺历史列表 -->
      <div v-if="activeTab === 'stores'" class="history-content">
        <div v-if="storeHistory.length > 0" class="store-history-list">
          <div v-for="store in storeHistory" :key="store.id" class="history-item store-item">
            <div class="item-cover" @click="goToStore(store.id)">
              <el-image 
                :src="store.coverImage" 
                fit="cover"
                :lazy="true"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            
            <div class="item-content" @click="goToStore(store.id)">
              <div class="item-name">{{ store.name }}</div>
              
              <div class="item-info">
                <div class="rating">
                  <star-rating :score="store.rating" :show-score="true" size="small" />
                </div>
                <div class="sales">月售 {{ store.monthSales }}+ 单</div>
              </div>
              
              <div class="item-tags">
                <el-tag 
                  v-for="(tag, index) in store.tags" 
                  :key="index"
                  size="small"
                  effect="plain"
                >
                  {{ tag }}
                </el-tag>
              </div>
              
              <div class="item-meta">
                <span class="delivery-info">{{ store.deliveryTime }}分钟 | 配送费¥{{ store.deliveryFee }}</span>
                <span class="visit-time">{{ formatTime(store.visitTime) }}</span>
              </div>
            </div>
            
            <div class="item-actions">
              <el-button 
                @click.stop="removeFromHistory('store', store.historyId)" 
                link 
                size="middle"
                class="remove-btn"
              >
                <el-icon style="color: red;"><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-state">
          <el-empty description="暂无店铺浏览历史">
            <el-button type="primary" @click="goToStoreList">去逛逛</el-button>
          </el-empty>
        </div>
      </div>
      
      <!-- 商品历史列表 -->
      <div v-if="activeTab === 'foods'" class="history-content">
        <div v-if="foodHistory.length > 0" class="food-history-list">
          <div v-for="food in foodHistory" :key="food.id" class="history-item food-item">
            <div class="item-image" @click="goToFood(food.id, food.storeId)">
              <el-image 
                :src="food.image" 
                fit="cover"
                :lazy="true"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            
            <div class="item-content" @click="goToFood(food.id, food.storeId)">
              <div class="item-name">{{ food.name }}</div>
              
              <div v-if="food.description" class="item-description">
                {{ food.description }}
              </div>
              
              <div class="item-store" v-if="food.storeName">
                来自: {{ food.storeName }}
              </div>
              
              <div class="item-stats">
                <div class="rating">
                  <star-rating :score="food.rating" :show-score="true" size="small" />
                </div>
                <div class="sales">月售 {{ food.monthlySales }}+</div>
              </div>
              
              <div class="item-meta">
                <span class="price">¥{{ food.price }}</span>
                <span class="visit-time">{{ formatTime(food.visitTime) }}</span>
              </div>
            </div>
            
            <div class="item-actions">
              <el-button 
                @click.stop="removeFromHistory('food', food.historyId)" 
                link 
                size="small"
                class="remove-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-state">
          <el-empty description="暂无商品浏览历史">
            <el-button type="primary" @click="goToStoreList">去逛逛</el-button>
          </el-empty>
        </div>
      </div>
      
      <!-- 分页 - 历史记录接口不支持分页，暂时隐藏 -->
      <div v-if="false" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="activeTab === 'stores' ? storeTotal : foodTotal"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture, Delete } from '@element-plus/icons-vue';
import CustomerLayout from "@/components/customer/CustomerLayout.vue";
import StarRating from "@/components/common/StarRating.vue";
import { historyApi } from '@/api/customer';
import { Store, Food } from '@/types/customer';

// 扩展类型定义
interface HistoryStore extends Store {
  visitTime: string;
  deliveryFee: number;
  historyId: number;
}

interface HistoryFood extends Food {
  visitTime: string;
  storeId: number;
  storeName: string;
  historyId: number;
}

// 定义 API 响应类型
interface HistoryResponse<T> {
  data: T[] | { content: T[] };
}

const router = useRouter();

// 响应式数据
const activeTab = ref('stores');
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 历史记录数据
const storeHistory = ref<HistoryStore[]>([]);
const foodHistory = ref<HistoryFood[]>([]);
const storeTotal = ref(0);
const foodTotal = ref(0);

// 获取店铺浏览历史
const fetchStoreHistory = async () => {
  try {
    loading.value = true;
    const res = await historyApi.getStores() as any;
    
    console.log('Store history response:', res);
    console.log('Store history response type:', typeof res);
    console.log('Store history response keys:', Object.keys(res || {}));
    
    // 尝试多种可能的数据结构
    let stores: any[] = [];
    
    // 检查各种可能的响应结构
    if (res) {
      // 情况1: 直接是数组
      if (Array.isArray(res)) {
        stores = res;
        console.log('发现直接数组格式');
      }
      // 情况2: res.data 是数组
      else if (Array.isArray(res.data)) {
        stores = res.data;
        console.log('发现 res.data 数组格式');
      }
      // 情况3: res.data.content 是数组（分页格式）
      else if (res.data && Array.isArray(res.data.content)) {
        stores = res.data.content;
        console.log('发现 res.data.content 分页格式');
      }
      // 情况4: res.data.data 是数组（嵌套格式）
      else if (res.data && res.data.data && Array.isArray(res.data.data)) {
        stores = res.data.data;
        console.log('发现 res.data.data 嵌套格式');
      }
      // 情况5: 其他可能的嵌套结构
      else if (res.data && res.data.data && res.data.data.content && Array.isArray(res.data.data.content)) {
        stores = res.data.data.content;
        console.log('发现深度嵌套分页格式');
      }
      // 其他情况，尝试查找数组
      else {
        console.warn('未识别的响应格式，尝试查找数组字段:', res);
        
        // 递归查找数组字段
        const findArray = (obj: any): any[] => {
          if (Array.isArray(obj)) return obj;
          if (typeof obj === 'object' && obj !== null) {
            for (const key in obj) {
              if (Array.isArray(obj[key])) {
                console.log(`找到数组字段: ${key}`, obj[key]);
                return obj[key];
              } else if (typeof obj[key] === 'object') {
                const result = findArray(obj[key]);
                if (result.length > 0) return result;
              }
            }
          }
          return [];
        };
        
        stores = findArray(res);
      }
    }
    
    console.log('最终解析的店铺数据:', stores);
    console.log('店铺数据类型:', typeof stores, 'isArray:', Array.isArray(stores));
    
    // 确保 stores 是数组
    if (!Array.isArray(stores)) {
      console.warn('stores 不是数组，设置为空数组');
      stores = [];
    }
    
    storeTotal.value = stores.length;
    
    storeHistory.value = stores.map((item: any) => ({
      ...item,
      historyId: item.historyId || item.id, // 保存历史记录ID用于删除
      visitTime: item.visitedAt || item.visitTime || new Date().toISOString(),
      deliveryFee: item.deliveryFee || 3,
      // 确保必要字段存在
      rating: item.rating || 0,
      monthSales: item.monthSales || 0,
      deliveryTime: item.averageDeliveryTime || item.deliveryTime || 30,
      tags: item.tags || [],
      coverImage: item.logo || item.coverImage || '/images/store.png'
    }));
    
    console.log('处理后的店铺历史:', storeHistory.value);
  } catch (error) {
    console.error('获取店铺浏览历史失败:', error);
    ElMessage.error('获取店铺浏览历史失败');
  } finally {
    loading.value = false;
  }
};

// 获取商品浏览历史
const fetchFoodHistory = async () => {
  try {
    loading.value = true;
    const res = await historyApi.getFoods() as any;
    
    console.log('Food history response:', res);
    console.log('Food history response type:', typeof res);
    console.log('Food history response keys:', Object.keys(res || {}));
    
    // 尝试多种可能的数据结构
    let foods: any[] = [];
    
    // 检查各种可能的响应结构
    if (res) {
      // 情况1: 直接是数组
      if (Array.isArray(res)) {
        foods = res;
        console.log('发现直接数组格式');
      }
      // 情况2: res.data 是数组
      else if (Array.isArray(res.data)) {
        foods = res.data;
        console.log('发现 res.data 数组格式');
      }
      // 情况3: res.data.content 是数组（分页格式）
      else if (res.data && Array.isArray(res.data.content)) {
        foods = res.data.content;
        console.log('发现 res.data.content 分页格式');
      }
      // 情况4: res.data.data 是数组（嵌套格式）
      else if (res.data && res.data.data && Array.isArray(res.data.data)) {
        foods = res.data.data;
        console.log('发现 res.data.data 嵌套格式');
      }
      // 情况5: 其他可能的嵌套结构
      else if (res.data && res.data.data && res.data.data.content && Array.isArray(res.data.data.content)) {
        foods = res.data.data.content;
        console.log('发现深度嵌套分页格式');
      }
      // 其他情况，尝试查找数组
      else {
        console.warn('未识别的响应格式，尝试查找数组字段:', res);
        
        // 递归查找数组字段
        const findArray = (obj: any): any[] => {
          if (Array.isArray(obj)) return obj;
          if (typeof obj === 'object' && obj !== null) {
            for (const key in obj) {
              if (Array.isArray(obj[key])) {
                console.log(`找到数组字段: ${key}`, obj[key]);
                return obj[key];
              } else if (typeof obj[key] === 'object') {
                const result = findArray(obj[key]);
                if (result.length > 0) return result;
              }
            }
          }
          return [];
        };
        
        foods = findArray(res);
      }
    }
    
    console.log('最终解析的食物数据:', foods);
    console.log('食物数据类型:', typeof foods, 'isArray:', Array.isArray(foods));
    
    // 确保 foods 是数组
    if (!Array.isArray(foods)) {
      console.warn('foods 不是数组，设置为空数组');
      foods = [];
    }
    
    foodTotal.value = foods.length;
    
    foodHistory.value = foods.map((item: any) => ({
      ...item,
      historyId: item.historyId || item.id, // 保存历史记录ID用于删除
      visitTime: item.visitedAt || item.visitTime || new Date().toISOString(),
      storeId: item.storeId || 1,
      storeName: item.storeName || '未知店铺',
      // 确保必要字段存在
      rating: item.rating || 0,
      monthlySales: item.monthlySales || item.monthSales || 0,
      price: item.price || 0,
      description: item.description || '',
      image: item.image || '/images/food.png'
    }));
    
    console.log('处理后的食物历史:', foodHistory.value);
  } catch (error) {
    console.error('获取商品浏览历史失败:', error);
    ElMessage.error('获取商品浏览历史失败');
  } finally {
    loading.value = false;
  }
};

// 格式化时间 - 增强版本，与微信小程序保持一致
const formatTime = (time: string): string => {
  const date = new Date(time);
  const now = new Date();
  const today = new Date().toISOString().split('T')[0];
  const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0];
  const itemDate = time.split('T')[0];
  
  if (itemDate === today) {
    // 今天的显示具体时间
    const diff = now.getTime() - date.getTime();
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor(diff / (1000 * 60));
    
    if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else {
      return '刚刚';
    }
  } else if (itemDate === yesterday) {
    return '昨天';
  } else {
    // 显示具体日期
    const [year, month, day] = itemDate.split('-');
    const currentYear = new Date().getFullYear().toString();
    if (year === currentYear) {
      return `${parseInt(month)}月${parseInt(day)}日`;
    } else {
      return `${year}年${parseInt(month)}月${parseInt(day)}日`;
    }
  }
};

// 切换标签页
const handleTabChange = (tab: any) => {
  if (tab.name === 'stores') {
    fetchStoreHistory();
  } else {
    fetchFoodHistory();
  }
};

// 分页处理 - 由于接口不支持分页，这里移除分页功能
const handlePageChange = (page: number) => {
  // 历史记录接口不支持分页，保留方法以避免模板报错
};

const handleSizeChange = (size: number) => {
  // 历史记录接口不支持分页，保留方法以避免模板报错
};

// 导航功能
const goToStore = (storeId: number) => {
  // 查找店铺信息以检查状态
  const store = storeHistory.value.find(s => s.id === storeId);
  if (store && store.status && store.status !== 'OPEN') {
    ElMessage.error('店铺未营业');
    return;
  }
  router.push(`/customer/store/${storeId}`);
};

const goToFood = (foodId: number, storeId: number) => {
  // 跳转到店铺页面，并可能需要打开商品详情
  router.push(`/customer/store/${storeId}?foodId=${foodId}`);
};

const goToStoreList = () => {
  router.push('/customer/stores');
};

// 从历史记录中移除
const removeFromHistory = (type: 'store' | 'food', historyId: number) => {
  ElMessageBox.confirm(
    `确定要从浏览历史中移除这个${type === 'store' ? '店铺' : '商品'}吗？`,
    '移除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用API删除历史记录 - 使用 historyId
      await historyApi.deleteHistory(historyId);
      
      // 从本地数组中移除
      if (type === 'store') {
        storeHistory.value = storeHistory.value.filter(item => item.historyId !== historyId);
        storeTotal.value--;
      } else {
        foodHistory.value = foodHistory.value.filter(item => item.historyId !== historyId);
        foodTotal.value--;
      }
      
      ElMessage.success('已移除');
    } catch (error) {
      console.error('移除历史记录失败:', error);
      ElMessage.error('移除失败');
    }
  }).catch(() => {
    // 用户取消操作
  });
};


// 组件挂载时获取数据
onMounted(() => {
  fetchStoreHistory();
});
</script>

<style scoped>
.history-container {
  max-width: 95%;
  margin: 0 auto;
  padding: 20px;
  min-width: 320px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.history-tabs {
  margin-bottom: 20px;
}

.history-content {
  min-height: 400px;
}

/* 历史记录项通用样式 */
.history-item {
  display: flex;
  padding: 15px;
  margin-bottom: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.item-cover,
.item-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 15px;
  flex-shrink: 0;
}

.item-cover img,
.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
  color: #ccc;
  font-size: 24px;
}

.item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.2;
}

.item-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-store {
  color: #999;
  font-size: 12px;
  margin-bottom: 8px;
}

.item-info,
.item-stats {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 8px;
}

.rating {
  display: flex;
  align-items: center;
}

.sales {
  color: #666;
  font-size: 12px;
}

.item-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 8px;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.delivery-info {
  color: #666;
}

.price {
  color: #ff6600;
  font-weight: 600;
  font-size: 14px;
}

.visit-time {
  color: #999;
}

.item-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-left: 15px;
}

.remove-btn {
  color: #999;
  padding: 8px;
}

.remove-btn:hover {
  color: #ff4757;
  background-color: #fff5f5;
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-container {
    padding: 15px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .history-item {
    padding: 12px;
  }
  
  .item-cover,
  .item-image {
    width: 80px;
    height: 80px;
    margin-right: 12px;
  }
  
  .item-name {
    font-size: 16px;
  }
  
  .item-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .item-actions {
    margin-left: 10px;
  }
}
</style>
